/**
 * @file 首页
 * @module pages/index
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires config/navbar - 导航栏配置
 * @requires config/topic - 主题配置
 * @requires libs/router - 路由跳转
 * @requires models/version - 版本控制
 * @requires libs/tools - 工具方法
 * @requires libs/proxy - 代理类
 */
import { index_navbars } from '../../config/navbar';
import { TOPIC, music_center, topics } from '../../config/topic';
import router from '../../libs/router';
import versionModel from '../../models/version';
import tools from '../../libs/tools';
import { createPageProxy } from '../../libs/proxy';

// 获取数据仓库
const { $store } = getApp();
 
createPageProxy($store)({
  /**
   * @property {string} $topic - 当前主题
   * @property {object} navbars - 导航栏配置
   * @property {object} cure - 中心主题配置
   * @property {object} list - 主题列表配置
   * @property {boolean} hideModule - 是否隐藏模块
   * @property {boolean} loading - 加载中
   */
  data: {
    $topic: $store.state.topic,
    navbars: index_navbars,
    center: music_center,
    list: topics[$store.state.topic],
    hideModule: false,
    loading: true
  },

  onLoad: function () {
    // 初始化函数
    this.init();
  },

  /**
   * @description 初始化函数
   * @returns {void}
   */
  init () {
    // 获取版本号
    this.getVersion();
  },

  /**
   * @description 获取版本号，控制视图显示
   * @returns {void}
   */
  async getVersion () {
    const { result } = await versionModel.getVersion(),
          local_version = $store.state.version;

    if (result) {
      const { version } = result;

      if (version === local_version) {
        this.setData({
          hideModule: true,
          loading: false
        });
        return;
      }

      this.setData({
        loading: false,
        $topic: TOPIC.MUSIC,
        list: topics[TOPIC.MUSIC]
      });
    }
  },

  /**
   * @description 导航栏切换
   * @param {object} e - 事件源
   * @returns void 
   */
  onNavbarClick (e) {
    const { field } = e.currentTarget.dataset,
          $topic = this.data.$topic;
    
    if ($topic === field) return;

    switch (field) {
      case TOPIC.MUSIC:
      case TOPIC.STORY:
        this.setData({
          $topic: field,
          list: topics[field]
        });
        break;
      case TOPIC.MY:
        tools.showToast('正在开发中');
        break;
      default:
        break;
    }
  },

  /**
   * @description 主题点击处理
   * @param {object} e - 事件源
   * @returns void 
   */
  onTopicClick (e) {
    const { action } = e.currentTarget.dataset;

    // 提交数据
    $store.commit('changeState', {
      type: action
    });

    // 跳转主题页
    router.navigate(`/pages/topic/topic`);
  }
})
